package org.cosmact.designer.vxml.gefeditor.editpart;

import org.cosmact.vxml.model.DialogConnection;
import org.eclipse.draw2d.Graphics;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.Label;
import org.eclipse.draw2d.MidpointLocator;
import org.eclipse.draw2d.PolygonDecoration;
import org.eclipse.draw2d.PolylineConnection;
import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.gef.LayerConstants;
import org.eclipse.gef.editparts.AbstractConnectionEditPart;

/**
 * TODO Multi-extends problem
 * <p>
 * How to custom the connection? see <a href=
 * "http://www.ibm.com/developerworks/cn/opensource/os-ecl-gef/part4/index.html"
 * >Connection tutorial</a>
 * 
 *@author YeXiaowei 234aini@gmail.com
 * 
 */
public class DialogConnectionEditPart extends AbstractConnectionEditPart
		implements LayerConstants {

	class ConnectionAdapter implements Adapter {

		@Override
		public Notifier getTarget() {
			return (Notifier) getModel();
		}

		@Override
		public boolean isAdapterForType(Object type) {
			return type.equals(getModel().getClass());
		}

		@Override
		public void setTarget(Notifier newTarget) {
			setModel(newTarget);
		}

		@Override
		public void notifyChanged(Notification notification) {
			// TODO LoggerHelper.debug(notification.getFeature().toString());
		}
	}

	private Adapter adapter = new ConnectionAdapter();

	@Override
	public void activate() {
		if (!isActive()) {
			super.activate();
			Notifier notified = (Notifier) getModel();
			notified.eAdapters().add(adapter);
		}
	}

	@Override
	public void deactivate() {
		if (isActive()) {
			super.deactivate();
			Notifier notified = (Notifier) getModel();
			notified.eAdapters().remove(adapter);
		}
	}

	@Override
	protected void createEditPolicies() {
		// TODO Auto-generated method stub
	}

	private DialogConnection getCastedModel() {
		return (DialogConnection) getModel();
	}

	@Override
	protected IFigure createFigure() {
		PolylineConnection connection = (PolylineConnection) super
				.createFigure();
		connection.setTargetDecoration(new PolygonDecoration());
		connection.setLineStyle(Graphics.LINE_SOLID);

		addLabelToConnection(connection);
		return connection;
	}

	private void addLabelToConnection(PolylineConnection connection) {
		final Label label = new Label(getCastedModel().getConnectionType()
				.getType().getLiteral());
		label.setOpaque(false);
		connection.add(label, new MidpointLocator(connection, 0));
	}
}
